package com.ruoyi.flowable.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.flowable.domain.WfCategory;
import com.ruoyi.flowable.mapper.WfCategoryMapper;
import com.ruoyi.flowable.service.IWfCategoryService;
import org.springframework.stereotype.Service;

/**
 * 流程分类Service业务层处理
 *
 * @author siashan
 * @date 2022-12-29
 */
@Service
public class WfCategoryServiceImpl extends ServiceImpl<WfCategoryMapper, WfCategory> implements IWfCategoryService {

    /**
     * 校验是否唯一
     *
     * @param wfCategory 流程分类
     * @return 是否唯一
     */
    @Override
    public void checkUnique(WfCategory wfCategory) {
        LambdaQueryWrapper<WfCategory> lqw = new LambdaQueryWrapper<WfCategory>();
        lqw.eq(WfCategory::getCategoryName, wfCategory.getCategoryName());
        WfCategory one = getOne(lqw);
        Long reqCategoryId = wfCategory.getCategoryId();
        if (null == reqCategoryId) {
            // 如果是新增 one 存在说明名称重复
            if (null != one) {
                throw new ServiceException("已存在相同的分类名称", HttpStatus.BAD_REQUEST);
            }
        } else {
            // 如果是修改 one 不存在，说明名称不重复，one 存在 需要校验 ID 是否相同，相同说明不重复，不相同说明重复
            if (null != one) {
                if (reqCategoryId.longValue() != one.getCategoryId().longValue()) {
                    throw new ServiceException("已存在相同的分类名称", HttpStatus.BAD_REQUEST);
                }
            }
        }

        lqw.clear();
        lqw.eq(WfCategory::getCode, wfCategory.getCode());
        WfCategory oneByCode = getOne(lqw);

        if (null == reqCategoryId) {
            // 如果是新增 oneByCode 存在说明名称重复
            if (null != oneByCode) {
                throw new ServiceException("已存在相同的分类编码", HttpStatus.BAD_REQUEST);
            }
        } else {
            // 如果是修改 oneByCode 不存在，说明名称不重复，oneByCode 存在 需要校验 ID 是否相同，相同说明不重复，不相同说明重复
            if (null != oneByCode) {
                if (reqCategoryId.longValue() != oneByCode.getCategoryId().longValue()) {
                    throw new ServiceException("已存在相同的分类编码", HttpStatus.BAD_REQUEST);
                }
            }
        }


    }

    @Override
    public boolean checkCategoryCodeUnique(WfCategory category) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<WfCategory>()
                .eq(WfCategory::getCode, category.getCode())
                .ne(ObjectUtil.isNotNull(category.getCategoryId()), WfCategory::getCategoryId, category.getCategoryId()));
        return !exist;
    }
}
